<template>
  <div class="process-designer">
    <div class="process-tools">
      <div class="tool-group">
        <el-tooltip content="审批节点" placement="top">
          <div class="tool-item" @click="handleToolClick('approval')">
            <el-icon><User /></el-icon>
            <span>审批人</span>
          </div>
        </el-tooltip>
        <el-tooltip content="条件分支" placement="top">
          <div class="tool-item" @click="handleToolClick('condition')">
            <el-icon><Switch /></el-icon>
            <span>条件分支</span>
          </div>
        </el-tooltip>
        <el-tooltip content="并行分支" placement="top">
          <div class="tool-item" @click="handleToolClick('parallel')">
            <el-icon><Share /></el-icon>
            <span>并行分支</span>
          </div>
        </el-tooltip>
        <el-tooltip content="通知节点" placement="top">
          <div class="tool-item" @click="handleToolClick('notify')">
            <el-icon><Bell /></el-icon>
            <span>通知节点</span>
          </div>
        </el-tooltip>
      </div>
      <div class="tool-right">
        <el-upload
          class="upload-bpmn"
          accept=".bpmn,.xml"
          :show-file-list="false"
          :before-upload="handleImportBpmn"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>导入BPMN
          </el-button>
        </el-upload>
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>导出BPMN
        </el-button>
      </div>
    </div>

    <div class="process-canvas">
      <!-- 发起人节点 -->
      <div class="process-node start">
        <div class="node-content">
          <div class="node-header">
            <div class="node-title">
              <el-icon><User /></el-icon>
              <span>发起人</span>
            </div>
            <div class="node-actions">
              <el-button type="danger" link>
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="node-body">
            流程从本节点开始
          </div>
        </div>
        <div class="node-add">
          <el-dropdown trigger="click" @command="(type) => addNodeAfter(-1, type)">
            <el-button type="primary" circle size="small">
              <el-icon><Plus /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="approval">
                  <el-icon><User /></el-icon>审批节点
                </el-dropdown-item>
                <el-dropdown-item command="condition">
                  <el-icon><Switch /></el-icon>条件分支
                </el-dropdown-item>
                <el-dropdown-item command="parallel">
                  <el-icon><Share /></el-icon>并行分支
                </el-dropdown-item>
                <el-dropdown-item command="notify">
                  <el-icon><Bell /></el-icon>通知节点
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 流程节点 -->
      <div v-for="(node, index) in processNodes" :key="index">
        <!-- 条件分支节点 -->
        <template v-if="node.type === 'condition'">
          <div class="branch-node">
            <div class="branch-title">添加分支</div>
            <div class="branch-content">
              <div v-for="(branch, bIndex) in node.branches" :key="bIndex" class="branch-item">
                <div class="branch-header">
                  <div class="branch-label">
                    <el-icon><Share /></el-icon>
                    <span>条件{{ bIndex + 1 }}</span>
                    <span class="priority-label">优先级 {{ bIndex + 1 }}</span>
                  </div>
                  <div class="branch-actions">
                    <el-button type="danger" link @click="deleteBranch(index, bIndex)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="branch-body">
                  <div class="condition-text" @click="editBranchCondition(index, bIndex)">
                    {{ branch.condition || '请设置条件' }}
                  </div>
                  <div class="branch-nodes">
                    <!-- 分支内的节点列表 -->
                    <template v-for="(subNode, sIndex) in branch.nodes" :key="sIndex">
                      <div class="process-node" :class="subNode.type">
                        <div class="node-content">
                          <div class="node-header">
                            <div class="node-title">
                              <el-icon><component :is="subNode.icon" /></el-icon>
                              <span>{{ subNode.name }}</span>
                            </div>
                            <div class="node-actions">
                              <el-button type="danger" link @click="deleteSubNode(index, bIndex, sIndex)">
                                <el-icon><Delete /></el-icon>
                              </el-button>
                            </div>
                          </div>
                          <div class="node-body">
                            {{ subNode.approver || '请设置审批人' }}
                          </div>
                        </div>
                        <!-- 每个节点下都可以添加新节点 -->
                        <div class="node-add">
                          <el-dropdown trigger="click" @command="(type) => addNodeAfter(index, bIndex, sIndex, type)">
                            <el-button type="primary" circle size="small">
                              <el-icon><Plus /></el-icon>
                            </el-button>
                            <template #dropdown>
                              <el-dropdown-menu>
                                <el-dropdown-item command="approval">
                                  <el-icon><User /></el-icon>审批节点
                                </el-dropdown-item>
                                <el-dropdown-item command="condition">
                                  <el-icon><Switch /></el-icon>条件分支
                                </el-dropdown-item>
                                <el-dropdown-item command="notify">
                                  <el-icon><Bell /></el-icon>通知节点
                                </el-dropdown-item>
                              </el-dropdown-menu>
                            </template>
                          </el-dropdown>
                        </div>
                      </div>
                    </template>
                    <!-- 分支为空时显示添加按钮 -->
                    <div v-if="!branch.nodes.length" class="empty-branch">
                      <el-dropdown trigger="click" @command="(type) => addSubNode(index, bIndex, type)">
                        <el-button type="primary" plain>
                          <el-icon><Plus /></el-icon>添加节点
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="approval">
                              <el-icon><User /></el-icon>审批节点
                            </el-dropdown-item>
                            <el-dropdown-item command="condition">
                              <el-icon><Switch /></el-icon>条件分支
                            </el-dropdown-item>
                            <el-dropdown-item command="notify">
                              <el-icon><Bell /></el-icon>通知节点
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="branch-footer">
              <el-button type="primary" link @click="addBranchCondition(index)">
                <el-icon><Plus /></el-icon>添加条件
              </el-button>
            </div>
          </div>
        </template>

        <!-- 普通节点 -->
        <template v-else>
          <div class="process-node" :class="node.type">
            <div class="node-content">
              <div class="node-header">
                <div class="node-title">
                  <el-icon><User /></el-icon>
                  <span>{{ node.name }}</span>
                </div>
                <div class="node-actions">
                  <el-button type="danger" link @click="deleteNode(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <div class="node-body">
                发起人自己审批
              </div>
            </div>
            <div class="node-add">
              <el-dropdown trigger="click" @command="(type) => addNodeAfter(index, type)">
                <el-button type="primary" circle size="small">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="approval">
                      <el-icon><User /></el-icon>审批节点
                    </el-dropdown-item>
                    <el-dropdown-item command="condition">
                      <el-icon><Switch /></el-icon>条件分支
                    </el-dropdown-item>
                    <el-dropdown-item command="parallel">
                      <el-icon><Share /></el-icon>并行分支
                    </el-dropdown-item>
                    <el-dropdown-item command="notify">
                      <el-icon><Bell /></el-icon>通知节点
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </template>
      </div>

      <!-- 结束节点 -->
      <div class="process-node end">
        <div class="node-content">
          <el-icon><Select /></el-icon>
          <span>结束</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, Switch, Share, Bell, Connection, Download,
  TopRight, Select, Plus, Edit, Delete, Upload
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const processNodes = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const router = useRouter()

// 添加节点
const handleToolClick = (type) => {
  const nodeConfig = getNodeConfig(type)
  processNodes.value.push(nodeConfig)
}

// 在指定节点后添加新节点
const addNodeAfter = (index, type) => {
  const nodeConfig = getNodeConfig(type)
  if (index === -1) {
    processNodes.value.unshift(nodeConfig)
  } else {
    processNodes.value.splice(index + 1, 0, nodeConfig)
  }
}

// 删除节点
const deleteNode = (index) => {
  processNodes.value.splice(index, 1)
}

// 添加条件分支
const addBranchCondition = (index) => {
  processNodes.value[index].branches.push({
    condition: `条件${processNodes.value[index].branches.length + 1}`,
    nodes: []
  })
}

// 删除分支
const deleteBranch = (nodeIndex, branchIndex) => {
  processNodes.value[nodeIndex].branches.splice(branchIndex, 1)
}

// 添加子节点
const addSubNode = (nodeIndex, branchIndex, type) => {
  if (type === 'condition') {
    // 如果添加的是条件节点，直接使用条件节点的配置
    const conditionConfig = getNodeConfig('condition')
    processNodes.value[nodeIndex].branches[branchIndex].nodes.push(conditionConfig)
  } else {
    // 其他类型节点正常添加
    const nodeConfig = getNodeConfig(type)
    processNodes.value[nodeIndex].branches[branchIndex].nodes.push(nodeConfig)
  }
}

// 删除子节点
const deleteSubNode = (nodeIndex, branchIndex, subIndex) => {
  processNodes.value[nodeIndex].branches[branchIndex].nodes.splice(subIndex, 1)
}


// 获取节点配置
const getNodeConfig = (type) => {
  const configs = {
    approval: {
      type: 'approval',
      name: '审批节点',
      icon: 'User',
      approver: 'manager',
      approvalType: 'or'
    },
    condition: {
      type: 'condition',
      name: '条件分支',
      icon: 'Switch',
      branches: [
        { condition: '条件1', nodes: [] },
        { condition: '条2', nodes: [] }
      ]
    },
    parallel: {
      type: 'parallel',
      name: '并行分支',
      icon: 'Share',
      branches: [
        { nodes: [] },
        { nodes: [] }
      ]
    },
    notify: {
      type: 'notify',
      name: '通知节点',
      icon: 'Bell',
      notifyTypes: ['email'],
      notifyContent: ''
    }
  }
  return configs[type]
}

const handleNodeClick = (node, index) => {
  router.push({
    name: 'FlowNode',
    params: {
      type: node.type,
      id: index
    }
  })
}

// 添加编辑分支条件的方法
const editBranchCondition = (nodeIndex, branchIndex) => {
  // 打开条件编辑对话框
  router.push({
    name: 'FlowNode',
    params: {
      type: 'condition',
      id: `${nodeIndex}-${branchIndex}`
    }
  })
}

// 修改分支条件的方法
const updateBranchCondition = (nodeIndex, branchIndex, condition) => {
  if (processNodes.value[nodeIndex] && 
      processNodes.value[nodeIndex].branches && 
      processNodes.value[nodeIndex].branches[branchIndex]) {
    processNodes.value[nodeIndex].branches[branchIndex].condition = condition
  }
}

// 生成流程节点XML
const generateProcessXML = (nodes) => {
  let xml = ''
  let lastNodeId = 'startEvent'
  
  nodes.forEach((node, index) => {
    const currentNodeId = `Node_${index}`
    
    if (node.type === 'condition') {
      // 条件网关图形
      xml += `
      <exclusiveGateway id="${currentNodeId}_start" name="${node.name}">
        <incoming>Flow_${lastNodeId}_${currentNodeId}</incoming>
        ${node.branches.map((_, bIndex) => `
        <outgoing>Flow_${currentNodeId}_branch_${bIndex}</outgoing>`).join('')}
      </exclusiveGateway>`
      
      // 添加分支
      node.branches.forEach((branch, bIndex) => {
        xml += `
        <sequenceFlow id="Flow_${currentNodeId}_branch_${bIndex}"
                    sourceRef="${currentNodeId}_start"
                    targetRef="${currentNodeId}_branch_${bIndex}">
          <conditionExpression xsi:type="tFormalExpression">${branch.condition}</conditionExpression>
        </sequenceFlow>
        
        ${generateProcessXML(branch.nodes)}`
      })
      
    } else {
      // 普通节点
      xml += `
      <${getNodeType(node.type)} id="${currentNodeId}" name="${node.name}">
        <incoming>Flow_${lastNodeId}_${currentNodeId}</incoming>
        <outgoing>Flow_${currentNodeId}_next</outgoing>
      </${getNodeType(node.type)}>`
    }
    
    lastNodeId = currentNodeId
  })
  
  return xml
}

// 获取节点类型
const getNodeType = (type) => {
  const types = {
    approval: 'userTask',
    notify: 'serviceTask',
    subprocess: 'subProcess',
    parallel: 'parallelGateway'
  }
  return types[type] || 'task'
}

// 修改生成 BPMN XML 的方法
const generateBPMN = (nodes) => {
  const processId = 'Process_' + Date.now()
  
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:flowable="http://flowable.org/bpmn"
             xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
             xmlns:dc="http://www.omg.org/spec/DD/20100524/DC"
             xmlns:di="http://www.omg.org/spec/DD/20100524/DI"
             targetNamespace="http://flowable.org/processes">
  <process id="${processId}" name="审批流程" isExecutable="true">
    <startEvent id="startEvent" name="开始" flowable:initiator="initiator">
      <outgoing>Flow_0bhcjrw</outgoing>
    </startEvent>
    <userTask id="Node_0" name="审批节点">
      <incoming>Flow_0bhcjrw</incoming>
      <outgoing>Flow_1blvfib</outgoing>
    </userTask>
    <endEvent id="endEvent" name="结束">
      <incoming>Flow_1blvfib</incoming>
    </endEvent>
    <sequenceFlow id="Flow_0bhcjrw" sourceRef="startEvent" targetRef="Node_0" />
    <sequenceFlow id="Flow_1blvfib" sourceRef="Node_0" targetRef="endEvent" />
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_1">
    <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="${processId}">
      <bpmndi:BPMNEdge id="Flow_0bhcjrw_di" bpmnElement="Flow_0bhcjrw">
        <di:waypoint x="186" y="168" />
        <di:waypoint x="243" y="168" />
        <di:waypoint x="243" y="190" />
        <di:waypoint x="300" y="190" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge id="Flow_1blvfib_di" bpmnElement="Flow_1blvfib">
        <di:waypoint x="400" y="190" />
        <di:waypoint x="500" y="190" />
        <di:waypoint x="500" y="168" />
        <di:waypoint x="600" y="168" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape id="startEvent_di" bpmnElement="startEvent">
        <dc:Bounds x="150" y="150" width="36" height="36" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="Node_0_di" bpmnElement="Node_0">
        <dc:Bounds x="300" y="150" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="endEvent_di" bpmnElement="endEvent">
        <dc:Bounds x="600" y="150" width="36" height="36" />
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>`

  return xml
}

// 计算布局信息
const calculateLayout = (nodes) => {
  const layout = {
    startX: 150,
    startY: 150,
    endX: 150 + (nodes.length + 1) * 150,
    endY: 150,
    nodeSpacing: 150,
    branchSpacing: 100,
    nodes: []
  }
  
  let currentX = layout.startX + layout.nodeSpacing
  let currentY = layout.startY
  
  nodes.forEach((node, index) => {
    if (node.type === 'condition') {
      // 条件分支布局
      const branchLayout = {
        gateway: {
          x: currentX,
          y: currentY
        },
        branches: node.branches.map((branch, bIndex) => {
          const branchY = currentY - ((node.branches.length - 1) * layout.branchSpacing / 2) + bIndex * layout.branchSpacing
          return {
            x: currentX + layout.nodeSpacing,
            y: branchY,
            nodes: []
          }
        })
      }
      layout.nodes.push(branchLayout)
      currentX += layout.nodeSpacing * 2
    } else {
      // 普通节点布局
      layout.nodes.push({
        x: currentX,
        y: currentY
      })
      currentX += layout.nodeSpacing
    }
  })
  
  return layout
}

// 生成图形信息XML
const generateDiagramXML = (nodes, layout) => {
  let xml = ''
  let lastNodeId = 'startEvent'
  
  nodes.forEach((node, index) => {
    const currentNodeId = `Node_${index}`
    
    if (node.type === 'condition') {
      // 条件网关图形
      const nodeLayout = layout.nodes[index]
      xml += `
      <bpmndi:BPMNShape id="${currentNodeId}_start_di" bpmnElement="${currentNodeId}_start">
        <dc:Bounds x="${nodeLayout.gateway.x}" y="${nodeLayout.gateway.y}" width="50" height="50" />
      </bpmndi:BPMNShape>`
      
      // 分支节点图形
      node.branches.forEach((branch, bIndex) => {
        const branchLayout = nodeLayout.branches[bIndex]
        xml += `
        <bpmndi:BPMNShape id="${currentNodeId}_branch_${bIndex}_di" bpmnElement="${currentNodeId}_branch_${bIndex}">
          <dc:Bounds x="${branchLayout.x}" y="${branchLayout.y}" width="100" height="80" />
        </bpmndi:BPMNShape>`
      })
      
    } else {
      // 普通节点图形
      const nodeLayout = layout.nodes[index]
      xml += `
      <bpmndi:BPMNShape id="${currentNodeId}_di" bpmnElement="${currentNodeId}">
        <dc:Bounds x="${nodeLayout.x}" y="${nodeLayout.y}" width="100" height="80" />
      </bpmndi:BPMNShape>`
    }
  })
  
  return xml
}

// 修改生成连接线XML的方法
const generateSequenceFlowXML = (nodes, layout) => {
  let xml = ''
  let lastNodeId = 'startEvent'
  
  // 开始节点到第一个节点的连接线
  xml += `
    <bpmndi:BPMNEdge id="Flow_start_di" bpmnElement="Flow_start">
      <di:waypoint x="${layout.startX + 18}" y="${layout.startY + 18}" />
      <di:waypoint x="${layout.startX + layout.nodeSpacing / 2}" y="${layout.startY + 18}" />
      <di:waypoint x="${layout.startX + layout.nodeSpacing / 2}" y="${layout.startY + 18}" />
      <di:waypoint x="${layout.startX + layout.nodeSpacing}" y="${layout.startY + 18}" />
    </bpmndi:BPMNEdge>`
  
  nodes.forEach((node, index) => {
    const currentNodeId = `Node_${index}`
    const nodeLayout = layout.nodes[index]
    
    if (node.type === 'condition') {
      // 条件分支连接线
      node.branches.forEach((branch, bIndex) => {
        const branchLayout = nodeLayout.branches[bIndex]
        xml += `
        <bpmndi:BPMNEdge id="Flow_${currentNodeId}_branch_${bIndex}_di" bpmnElement="Flow_${currentNodeId}_branch_${bIndex}">
          <di:waypoint x="${nodeLayout.gateway.x + 25}" y="${nodeLayout.gateway.y + 25}" />
          <di:waypoint x="${nodeLayout.gateway.x + layout.nodeSpacing / 2}" y="${nodeLayout.gateway.y + 25}" />
          <di:waypoint x="${nodeLayout.gateway.x + layout.nodeSpacing / 2}" y="${branchLayout.y + 40}" />
          <di:waypoint x="${branchLayout.x}" y="${branchLayout.y + 40}" />
        </bpmndi:BPMNEdge>`
        
        // 分支内节点的连接线
        if (branch.nodes.length > 0) {
          let branchLastNodeId = `${currentNodeId}_branch_${bIndex}`
          branch.nodes.forEach((subNode, sIndex) => {
            const subNodeId = `${currentNodeId}_branch_${bIndex}_node_${sIndex}`
            xml += `
            <bpmndi:BPMNEdge id="Flow_${branchLastNodeId}_${subNodeId}_di" bpmnElement="Flow_${branchLastNodeId}_${subNodeId}">
              <di:waypoint x="${branchLayout.x + 100}" y="${branchLayout.y + 40}" />
              <di:waypoint x="${branchLayout.x + layout.nodeSpacing / 2}" y="${branchLayout.y + 40}" />
              <di:waypoint x="${branchLayout.x + layout.nodeSpacing / 2}" y="${branchLayout.y + 40}" />
              <di:waypoint x="${branchLayout.x + layout.nodeSpacing}" y="${branchLayout.y + 40}" />
            </bpmndi:BPMNEdge>`
            branchLastNodeId = subNodeId
          })
        }
      })
      
      // 分支合并后的连接线
      xml += `
      <bpmndi:BPMNEdge id="Flow_${currentNodeId}_merge_di" bpmnElement="Flow_${currentNodeId}_merge">
        <di:waypoint x="${nodeLayout.gateway.x + layout.nodeSpacing * 2}" y="${nodeLayout.gateway.y + 25}" />
        <di:waypoint x="${nodeLayout.gateway.x + layout.nodeSpacing * 2.5}" y="${nodeLayout.gateway.y + 25}" />
        <di:waypoint x="${nodeLayout.gateway.x + layout.nodeSpacing * 2.5}" y="${layout.startY + 18}" />
        <di:waypoint x="${nodeLayout.gateway.x + layout.nodeSpacing * 3}" y="${layout.startY + 18}" />
      </bpmndi:BPMNEdge>`
      
    } else {
      // 普通节点连接线
      xml += `
      <bpmndi:BPMNEdge id="Flow_${lastNodeId}_${currentNodeId}_di" bpmnElement="Flow_${lastNodeId}_${currentNodeId}">
        <di:waypoint x="${nodeLayout.x}" y="${nodeLayout.y + 40}" />
        <di:waypoint x="${nodeLayout.x + layout.nodeSpacing / 2}" y="${nodeLayout.y + 40}" />
        <di:waypoint x="${nodeLayout.x + layout.nodeSpacing / 2}" y="${nodeLayout.y + 40}" />
        <di:waypoint x="${nodeLayout.x + layout.nodeSpacing}" y="${nodeLayout.y + 40}" />
      </bpmndi:BPMNEdge>`
    }
    
    lastNodeId = currentNodeId
  })
  
  // 最后一个节点到结束节点的连接线
  xml += `
    <bpmndi:BPMNEdge id="Flow_end_di" bpmnElement="Flow_end">
      <di:waypoint x="${layout.endX - layout.nodeSpacing}" y="${layout.endY + 18}" />
      <di:waypoint x="${layout.endX - layout.nodeSpacing / 2}" y="${layout.endY + 18}" />
      <di:waypoint x="${layout.endX - layout.nodeSpacing / 2}" y="${layout.endY + 18}" />
      <di:waypoint x="${layout.endX}" y="${layout.endY + 18}" />
    </bpmndi:BPMNEdge>`
  
  return xml
}

// 添加导出方法
const handleExport = () => {
  const bpmnXML = generateBPMN(processNodes.value)
  downloadFile('process.bpmn', bpmnXML)
}

// 下载文件方法
const downloadFile = (filename, content) => {
  const blob = new Blob([content], { type: 'text/xml' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

// 添加导入BPMN的方法
const handleImportBpmn = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const xml = e.target.result
    parseBpmnXml(xml)
  }
  reader.readAsText(file)
  return false // 阻止自动上传
}

// 解析BPMN XML
const parseBpmnXml = (xml) => {
  try {
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(xml, 'text/xml')
    
    // 清空现有节点
    processNodes.value = []
    
    // 获取所有任务节点
    const tasks = xmlDoc.getElementsByTagName('userTask')
    Array.from(tasks).forEach(task => {
      processNodes.value.push({
        type: 'approval',
        name: task.getAttribute('name') || '审批节点',
        icon: 'User',
        approver: task.getAttribute('flowable:assignee') || 'manager',
        approvalType: task.getAttribute('flowable:candidateGroups')?.includes('managers') ? 'or' : 'and'
      })
    })
    
    // 获取条件网关
    const gateways = xmlDoc.getElementsByTagName('exclusiveGateway')
    Array.from(gateways).forEach(gateway => {
      const branches = []
      const outgoing = gateway.getElementsByTagName('outgoing')
      Array.from(outgoing).forEach(flow => {
        const flowId = flow.textContent
        const sequenceFlow = xmlDoc.querySelector(`sequenceFlow[id="${flowId}"]`)
        const condition = sequenceFlow?.querySelector('conditionExpression')?.textContent
        
        branches.push({
          condition: condition || '条件分支',
          nodes: []
        })
      })
      
      if (branches.length > 0) {
        processNodes.value.push({
          type: 'condition',
          name: gateway.getAttribute('name') || '条件分支',
          icon: 'Switch',
          branches
        })
      }
    })
    
    // 获取服务任务(通知节点)
    const serviceTasks = xmlDoc.getElementsByTagName('serviceTask')
    Array.from(serviceTasks).forEach(task => {
      processNodes.value.push({
        type: 'notify',
        name: task.getAttribute('name') || '通知节点',
        icon: 'Bell',
        notifyTypes: ['email'],
        notifyContent: ''
      })
    })
    
    ElMessage.success('导入成功')
  } catch (error) {
    console.error('解析BPMN XML失败:', error)
    ElMessage.error('导入失败，请检查文件格式')
  }
}
</script>

<style scoped>
.process-designer {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.process-tools {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tool-group {
  display: flex;
  gap: 16px;
}

.tool-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background: #f5f7fa;
  min-width: 80px;
}

.tool-item:hover {
  background: #e6f7ff;
  transform: translateY(-2px);
}

.tool-item .el-icon {
  font-size: 24px;
  color: #1890ff;
}

.tool-item span {
  font-size: 12px;
  color: #666;
}

.process-canvas {
  padding: 40px;
  min-height: 400px;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32px;
}

.process-node {
  position: relative;
  width: 100%;
  max-width: 200px;
  margin: 0 auto;
}

.node-content {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.node-header {
  padding: 8px 12px;
  background: #e6f7ff;
  border-bottom: 1px solid #91d5ff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.node-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-title .el-icon {
  font-size: 16px;
  color: #1890ff;
}

.node-title span {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.node-body {
  padding: 12px;
  color: #666;
  font-size: 12px;
  text-align: center;
}

.node-actions {
  display: flex;
  gap: 4px;
}

.node-actions .el-button {
  padding: 4px;
}

.node-actions .el-icon {
  font-size: 14px;
}

/* 添加节点按钮样式 */
.node-add {
  position: absolute;
  left: 50%;
  bottom: -16px;
  transform: translateX(-50%);
  z-index: 10;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.node-add .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
  font-size: 16px;
}

/* 连接线样式 */
.process-node::before {
  content: '';
  position: absolute;
  top: -32px;
  left: 50%;
  width: 2px;
  height: 32px;
  background: #1890ff;
  transform: translateX(-50%);
}

/* 添加箭头 */
.process-node::after {
  content: '';
  position: absolute;
  top: -8px;
  left: 50%;
  transform: translateX(-50%) rotate(45deg);
  width: 8px;
  height: 8px;
  border-right: 2px solid #1890ff;
  border-bottom: 2px solid #1890ff;
}

/* 分支节点连接线 */
.branch-node {
  position: relative;
}

/* 分支前的垂直连接线 */
.branch-node::before {
  content: '';
  position: absolute;
  top: -32px;
  left: 50%;
  width: 2px;
  height: 32px;
  background: #1890ff;
  transform: translateX(-50%);
}

/* 分支后的垂直连接线 */
.branch-node::after {
  content: '';
  position: absolute;
  bottom: -32px;
  left: 50%;
  width: 2px;
  height: 32px;
  background: #1890ff;
  transform: translateX(-50%);
}

/* 分支内部连接线 */
.branch-content {
  position: relative;
}

/* 分支水平连接线 */
.branch-content::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: 2px;
  background: #1890ff;
  transform: translateY(-50%);
  z-index: 0;
}

/* 分支项连接线 */
.branch-item {
  position: relative;
}

/* 分支项垂直连接线 */
.branch-item::before {
  content: '';
  position: absolute;
  top: -20px;
  left: 50%;
  width: 2px;
  height: 20px;
  background: #1890ff;
  transform: translateX(-50%);
}

/* 分支内节点连接线 */
.branch-nodes {
  position: relative;
}

.branch-nodes::before {
  content: '';
  position: absolute;
  top: 0;
  left: 50%;
  width: 2px;
  height: 100%;
  background: #1890ff;
  transform: translateX(-50%);
  z-index: 0;
}

/* 添加连接线动画 */
.process-node::before,
.process-node::after,
.branch-node::before,
.branch-node::after,
.branch-content::before,
.branch-item::before,
.branch-nodes::before,
.node-add::before {
  animation: flowLine 0.3s ease-out forwards;
}

@keyframes flowLine {
  from {
    opacity: 0;
    transform: scaleY(0);
  }
  to {
    opacity: 1;
    transform: scaleY(1);
  }
}

/* 隐藏第一个节点的上连接线 */
.process-node:first-child::before {
  display: none;
}

/* 隐藏最后一个节点的下连接线 */
.process-node:last-child .node-add {
  display: none;
}

/* 优化节点间距 */
.process-node {
  margin-bottom: 48px;  /* 增加节点间距 */
}

.branch-node {
  margin: 48px 0;  /* 增加分支节点间距 */
}

.branch-item {
  padding-top: 32px;  /* 增加分支项上间距 */
}

/* 确保节点内容在连接线上层 */
.node-content {
  position: relative;
  z-index: 1;
  background: #fff;
}

/* 分支内容区域样式 */
.branch-content {
  display: flex;
  gap: 24px;
  padding: 32px 16px;
  background: #fafafa;
  border-radius: 4px;
  margin-top: 16px;
}

.branch-item {
  flex: 1;
  min-width: 0;
  background: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  padding: 16px;
  position: relative;
}

/* 添加箭头样式 */
.process-node::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  width: 8px;
  height: 8px;
  border-right: 2px solid #1890ff;
  border-bottom: 2px solid #1890ff;
  transform: translateX(-50%) rotate(45deg);
}

.tool-right {
  display: flex;
  gap: 12px;
}

.upload-bpmn {
  display: inline-block;
}
</style> 